package com.ybu.controller;

import com.ybu.common.Constants;
import com.ybu.common.JwtUtils;
import com.ybu.common.R;
import com.ybu.pojo.dto.CartDTO;
import com.ybu.pojo.vo.CartVO;
import com.ybu.pojo.vo.UserLoginVO;
import com.ybu.service.CartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@RestController
@RequestMapping("api/cart")
public class CartController {
    @Autowired
    private CartService cartService;
    @GetMapping("list")
    public R<List<CartVO>> getCartList(HttpServletRequest request){
        String token = request.getHeader(Constants.TOKEN_HEADER);
        UserLoginVO userLoginVO = JwtUtils.parseToken(token);
        List<CartVO> cartList = cartService.getCartList(userLoginVO);
        return R.ok(cartList);
    }
    @DeleteMapping("/removeItem")
    public R<Void> deleteCartItem(@RequestBody Integer[] ids,@RequestHeader("Authorization")
        String token) {
        UserLoginVO userLoginVO = JwtUtils.parseToken(token);
        // 调用业务层处理购物车商品删除的业务
        cartService.deleteCartItem(ids, userLoginVO.getId());

        return R.ok(); // 假设R是一个通用的响应类
    }


    @PostMapping("/update")
    public R<List<CartVO>> update(@RequestBody CartDTO cartDTO, @RequestHeader("Authorization") String token) {
        UserLoginVO userLoginVO = JwtUtils.parseToken(token);
        List<CartVO> cartVOList = cartService.update(cartDTO.getId(), userLoginVO.getId(), cartDTO.getProductId(), cartDTO.getNum());
        return R.ok(cartVOList);
    }
}
